<template>
  <div class="tree-select-container" @click="handleClick">
    <div class="tree-select-body">
      <ASpin :spinning="loading">
        <AEmpty v-if="!props.treeData || props.treeData?.length === 0" />

        <ACheckboxGroup v-else class="tree-select-checkbox-group" :value="props.selectKeys" @change="handleChange">
          <TreeSelectItem
            v-for="item in props?.treeData"
            :key="item.value"
            :data="item"
            :expandedKeys="expandedKeys"
          ></TreeSelectItem>
        </ACheckboxGroup>
      </ASpin>
    </div>
  </div>
</template>

<script setup>
import { toValue } from 'vue';
import { TreeSelectItem } from './modules';

defineOptions({
  name: 'RTreeSelect',
  inheritAttrs: false
});

const props = defineProps({
  treeData: { type: Array, default: () => [] },
  selectKeys: { type: Array, default: () => [] },
  expandedKeys: { type: Array, default: () => [], required: true },
  loading: { type: Boolean, default: false },
  onChange: Function
});

const emit = defineEmits(['update:expandedKeys', 'update:selectKeys']);

const handleChange = (values) => {
  emit('update:selectKeys', values);
  props.onChange?.(values);
};

const handleClick = (e) => {
  // 点击处理
  const expandDom = e.target?.closest('[data-expand]');
  if (expandDom) {
    const value = expandDom?.getAttribute('data-expand');
    value && handleExpand(value);
  }
};

const handleExpand = (v) => {
  // 单项展开处理 v: treeData[?].value
  const [...values] = toValue(props.expandedKeys);
  const index = values?.findIndex((t) => t === v);
  index === -1 ? values?.push(v) : values?.splice(index, 1);
  emit('update:expandedKeys', values);
};
</script>

<style lang="scss" scoped>
.tree-select-container {
  width: 100%;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid var(--border-color);
}
</style>
